package com.yyw.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyw.common.utils.PageUtils;
import com.yyw.common.utils.Query;
import com.yyw.gulimall.product.dao.CategoryDao;
import com.yyw.gulimall.product.entity.CategoryEntity;
import com.yyw.gulimall.product.service.CategoryBrandRelationService;
import com.yyw.gulimall.product.service.CategoryService;
import com.yyw.gulimall.product.vo.CategoryLevel1Vo;
import com.yyw.gulimall.product.vo.CategoryLevel2Vo;
import com.yyw.gulimall.product.vo.CategoryLevel3Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    /**
     * 品牌分类接口
     */
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> getTree() {
        // 1. 获取所有的菜单
        List<CategoryEntity> list = baseMapper.selectList(null);
        // 2.找到顶级菜单
        List<CategoryEntity> collect = list.stream().filter(e -> e.getParentCid() == 0)
                .map(e -> {
                    // 3. 递归查询子集
                    e.setChildren(getChildren(e, list));
                    return e;
                })
                .sorted((e1, e2) ->
                        Integer.compare(e1.getSort() == null ? 0 : e1.getSort(), e2.getSort() == null ? 0 : e2.getSort())
                ).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void delByIds(List<Long> asList) {
        // TODO: 2020/10/29 1.查询是否有相关联的数据
        // 2.逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    private List<CategoryEntity> getChildren(CategoryEntity entity, List<CategoryEntity> list) {
        List<CategoryEntity> collect = list.stream().filter(e -> e.getParentCid().equals(entity.getCatId()))
                .map(e -> {
                    e.setChildren(getChildren(e, list));
                    return e;
                }).sorted((e1, e2) ->
                        Integer.compare(e1.getSort() == null ? 0 : e1.getSort(), e2.getSort() == null ? 0 : e2.getSort())
                ).collect(Collectors.toList());
        return collect;
    }


    @Override
    public Long[] findCatelogPath(long catelogId) {
        List<Long> list = new ArrayList<>();
        List<Long> cateLogPath = getCateLogPath(catelogId, list);
        Collections.reverse(cateLogPath);

        return cateLogPath.toArray(new Long[cateLogPath.size()]);
    }

    /**
     * 失效模式：
     * 方式一:
     *
     * @param category
     * @CacheEvict(value = "category", allEntries = true)
     * 使用 allEntries=true 指定删除这个分区下面的所有数据
     * 方式二：
     * @Caching(evict = {
     * @CacheEvict(value = "category", key = "'categoryLevel1'"),
     * @CacheEvict(value = "category", key = "'getCategoryLevel2And3'"),
     * })
     * 使用 Caching组合多个注解
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict = {
            @CacheEvict(value = "category", key = "'categoryLevel1'"),
            @CacheEvict(value = "category", key = "'getCategoryLevel2And3'"),
    })
    public void updateCascade(CategoryEntity category) {
        // 修改自己
        this.updateById(category);
        // TODO: 2020/11/3 修改关联的数据
        // 修改品牌分类表
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

    /**
     * key 是纯字符时，要用单引号标注 key = "'categoryLevel1'" 因为只接受EL表达式
     *
     * @return
     */
    @Override
    @Cacheable(value = "category", key = "'categoryLevel1'")
    public List<CategoryLevel1Vo> getCategoryLevel1() {
        System.out.println(Thread.currentThread().getId() + "查询了数据库");
        List<CategoryEntity> list = this.list(new QueryWrapper<CategoryEntity>()
                .lambda().eq(CategoryEntity::getCatLevel, "1"));
        List<CategoryLevel1Vo> collect = null;
        if (!CollectionUtils.isEmpty(list)) {
            collect = list.stream().map(e -> {
                return CategoryLevel1Vo.builder().id(e.getCatId()).name(e.getName()).build();
            }).collect(Collectors.toList());
        }
        return collect;
    }

    /**
     * 使用cache注解
     * sync = true 是本地锁的设计，SpringCache并没有涉及到分布式锁的设计
     *
     * @return
     */
    @Cacheable(value = "category", key = "#root.methodName", sync = true)
    @Override
    public Map<String, List<CategoryLevel2Vo>> getCategoryLevel2And3() {
        System.out.println(Thread.currentThread().getId() + "查询了数据库");
        // 调用DB查询数据
        Map<String, List<CategoryLevel2Vo>> categoryListMap = getCategoryListMap();
        return categoryListMap;
    }

    /**
     * 分布式设计模式下的分布式锁
     * Resisson 解决分布式锁
     *
     * @return
     */
    public Map<String, List<CategoryLevel2Vo>> getCategoryLevel2And3ByRedisson() {
        // 从redis读取数据
        String categoryLevel2And3 = redisTemplate.opsForValue().get("categoryLevel2And3");
        if (StringUtils.isEmpty(categoryLevel2And3)) {
            // 加锁，没有获取到锁的线程会阻塞，只到拿到锁为止
            RLock lock = redissonClient.getLock("category-lock");
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getId() + "我拿到锁了");
                // 再次判断是否有数据
                categoryLevel2And3 = redisTemplate.opsForValue().get("categoryLevel2And3");
                if (StringUtils.isEmpty(categoryLevel2And3)) {
                    System.out.println(Thread.currentThread().getId() + "查询了数据库");
                    // 调用DB查询数据
                    Map<String, List<CategoryLevel2Vo>> categoryListMap = getCategoryListMap();
                    // 存Redis
                    redisTemplate.opsForValue().set("categoryLevel2And3", JSON.toJSONString(categoryListMap), 5, TimeUnit.MINUTES);
                    return categoryListMap;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 解锁
                lock.unlock();
            }
        }
        // 有数据 直接返回
        System.out.println(Thread.currentThread().getId() + "没有查询数据库");
        return JSON.parseObject(categoryLevel2And3, new TypeReference<Map<String, List<CategoryLevel2Vo>>>() {
        });

    }


    /**
     * 分布式设计模式下的分布式锁
     *
     * @return
     */
    public Map<String, List<CategoryLevel2Vo>> getCategoryLevel2And3ByRedis() {
        // 从redis读取数据
        String categoryLevel2And3 = redisTemplate.opsForValue().get("categoryLevel2And3");
        if (StringUtils.isEmpty(categoryLevel2And3)) {
            // 抢占分布式锁
            String uuid = UUID.randomUUID().toString();
            // 如果抢占成功就会存入成功，并且设置了过期时间300秒，
            // 可以设置大点，防止业务耗时长还没来得及存入redis锁就释放了，这样就会被其他的线程给占用
            Boolean look = redisTemplate.opsForValue().setIfAbsent("look", uuid, 300, TimeUnit.SECONDS);

            // 如果抢占成功
            if (look) {
                // 加锁成功，执行业务
                System.out.println(Thread.currentThread().getName() + "查询了数据库");
                // 调用DB查询数据
                Map<String, List<CategoryLevel2Vo>> categoryListMap = getCategoryListMap();
                // 存Redis
                redisTemplate.opsForValue().set("categoryLevel2And3", JSON.toJSONString(categoryListMap), 5, TimeUnit.MINUTES);

                // 删除锁脚本
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                // 删除锁，原子性，只有传过去的key查到的value和我们传过去的uuid一样的时候，才会删除锁
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("look"), uuid);
                return categoryListMap;
            } else {
                try {
                    System.out.println("我休眠了");
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 自旋，重复调用，直到执行完成
                return getCategoryLevel2And3();
            }
        } else {
            // 有数据
            // 直接返回
            System.out.println(Thread.currentThread().getName() + "没有查询数据库");
            return JSON.parseObject(categoryLevel2And3, new TypeReference<Map<String, List<CategoryLevel2Vo>>>() {
            });
        }
    }

    /**
     * 单体应用设计模式可行，分布式不行
     *
     * @return
     */
    public Map<String, List<CategoryLevel2Vo>> getCategoryLevel2And3One() {
        // 从redis读取数据
        String categoryLevel2And3 = redisTemplate.opsForValue().get("categoryLevel2And3");
        if (StringUtils.isEmpty(categoryLevel2And3)) {
            // 加锁
            synchronized (this) {
                // 再判断有没有
                if (StringUtils.isEmpty(redisTemplate.opsForValue().get("categoryLevel2And3"))) {
                    System.out.println(Thread.currentThread().getName() + "查询了数据库");
                    // 调用DB查询数据
                    Map<String, List<CategoryLevel2Vo>> categoryListMap = getCategoryListMap();
                    // 存Redis
                    redisTemplate.opsForValue().set("categoryLevel2And3", JSON.toJSONString(categoryListMap), 5, TimeUnit.MINUTES);
                    return categoryListMap;
                }
            }
        }
        // 直接返回
        System.out.println(Thread.currentThread().getName() + "没有查询数据库");
        return JSON.parseObject(categoryLevel2And3, new TypeReference<Map<String, List<CategoryLevel2Vo>>>() {
        });
    }


    /**
     * 方式一: 最原始的redis缓存
     * 缺点：容易造成多次查询数据库
     *
     * @return
     */
    public Map<String, List<CategoryLevel2Vo>> getCategoryLevel2And3ByRedis1() {
        String categoryLevel2And3 = redisTemplate.opsForValue().get("categoryLevel2And3");
        if (StringUtils.isEmpty(categoryLevel2And3)) {
            Map<String, List<CategoryLevel2Vo>> categoryListMap = getCategoryListMap();
            redisTemplate.opsForValue().set("categoryLevel2And3", JSON.toJSONString(categoryListMap));
            return categoryListMap;
        }
        System.out.println(Thread.currentThread().getName() + "没有查询数据库");
        return JSON.parseObject(categoryLevel2And3, new TypeReference<Map<String, List<CategoryLevel2Vo>>>() {
        });
    }

    /**
     * 查询首页三级分类数据
     *
     * @return
     */
    private Map<String, List<CategoryLevel2Vo>> getCategoryListMap() {
        // 查询全部数据
        List<CategoryEntity> all = this.list(null);
        if (!CollectionUtils.isEmpty(all)) {
            // 获取一级数据
            List<CategoryEntity> cateory1 = getCateoryByPid(all, 0L);
            // 封装map
            Map<String, List<CategoryLevel2Vo>> map = cateory1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),
                    v1 -> {
                        // 获取二级数据
                        List<CategoryEntity> cateory2 = getCateoryByPid(all, v1.getCatId());
                        List<CategoryLevel2Vo> collect = cateory2.stream().map(e -> {
                            // 获取三级数据
                            List<CategoryEntity> cateory3 = getCateoryByPid(all, e.getCatId());
                            List<CategoryLevel3Vo> collect3 = cateory3.stream().map(e3 -> {
                                CategoryLevel3Vo vo = CategoryLevel3Vo.builder().catalog2Id(e.getCatId()).id(e3.getCatId())
                                        .name(e3.getName()).build();
                                return vo;
                            }).collect(Collectors.toList());
                            // 封装二级数据
                            CategoryLevel2Vo vo = CategoryLevel2Vo.builder().catalog1Id(v1.getCatId()).id(e.getCatId())
                                    .name(e.getName()).catalog3List(collect3).build();
                            return vo;
                        }).collect(Collectors.toList());
                        return collect;
                    }));
            return map;
        }
        return null;
    }

    /**
     * 查询首页三级分类数据/根据父ID查询子分类
     *
     * @param all 所有的分类
     * @param pid 父分类ID
     * @return
     */
    private List<CategoryEntity> getCateoryByPid(List<CategoryEntity> all, long pid) {
        return all.stream().filter(e -> e.getParentCid() == pid).collect(Collectors.toList());
    }


    private List<Long> getCateLogPath(long catelogId, List<Long> list) {
        list.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (!Objects.isNull(categoryEntity) && categoryEntity.getParentCid() != 0) {
            getCateLogPath(categoryEntity.getParentCid(), list);
        }
        return list;
    }

}